package com.lzb.compressmaster.utils;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.ExifInterface;
import android.net.Uri;
import android.os.Build;
import android.util.Log;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;

public class PhotoPrivacyUtils {
    
    private static final String TAG = "PhotoPrivacyUtils";
    
    /**
     * 照片敏感信息实体类
     */
    public static class PhotoPrivacyInfo {
        public String cameraModel;      // 相机型号
        public String shootDate;        // 拍摄日期
        public String cameraMaker;      // 相机制造商
        public boolean flashFired;      // 闪光灯是否开启
        public boolean hasSensitiveInfo; // 是否包含敏感信息
        
        @Override
        public String toString() {
            return "PhotoPrivacyInfo{" +
                    "cameraModel='" + cameraModel + '\'' +
                    ", shootDate='" + shootDate + '\'' +
                    ", cameraMaker='" + cameraMaker + '\'' +
                    ", flashFired=" + flashFired +
                    ", hasSensitiveInfo=" + hasSensitiveInfo +
                    '}';
        }
    }
    
    /**
     * 获取照片的敏感信息
     * @param imagePath 图片路径
     * @return PhotoPrivacyInfo 敏感信息对象
     */
    public static PhotoPrivacyInfo getSensitiveInfo(String imagePath) {
        PhotoPrivacyInfo info = new PhotoPrivacyInfo();
        
        try {
            ExifInterface exif = new ExifInterface(imagePath);
            
            // 获取相机型号
            info.cameraModel = exif.getAttribute(ExifInterface.TAG_MODEL);
            
            // 获取拍摄日期
            String dateTime = exif.getAttribute(ExifInterface.TAG_DATETIME);
            if (dateTime != null) {
                try {
                    SimpleDateFormat inputFormat = new SimpleDateFormat("yyyy:MM:dd HH:mm:ss", Locale.getDefault());
                    SimpleDateFormat outputFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault());
                    Date date = inputFormat.parse(dateTime);
                    info.shootDate = outputFormat.format(date);
                } catch (Exception e) {
                    info.shootDate = dateTime;
                }
            }
            
            // 获取相机制造商
            info.cameraMaker = exif.getAttribute(ExifInterface.TAG_MAKE);
            
            // 获取闪光灯信息
            String flash = exif.getAttribute(ExifInterface.TAG_FLASH);
            if (flash != null) {
                try {
                    int flashValue = Integer.parseInt(flash);
                    info.flashFired = (flashValue & 1) == 1;
                } catch (NumberFormatException e) {
                    info.flashFired = false;
                }
            }
            
            // 检查是否包含敏感信息
            info.hasSensitiveInfo = (info.cameraModel != null && !info.cameraModel.isEmpty()) ||
                                   (info.shootDate != null && !info.shootDate.isEmpty()) ||
                                   (info.cameraMaker != null && !info.cameraMaker.isEmpty());
            
        } catch (IOException e) {
            Log.e(TAG, "读取EXIF信息失败: " + e.getMessage());
        }
        
        return info;
    }
    
    /**
     * 一键抹除照片的敏感信息
     * @param inputPath 输入图片路径
     * @param outputPath 输出图片路径（如果为null，则覆盖原图）
     * @return boolean 是否成功抹除
     */
    public static boolean eraseSensitiveInfo(String inputPath, String outputPath) {
        try {
            // 如果outputPath为null，使用临时文件
            boolean overwriteOriginal = (outputPath == null);
            if (overwriteOriginal) {
                outputPath = inputPath + ".tmp";
            }
            
            // 读取原始图片
            BitmapFactory.Options options = new BitmapFactory.Options();
            options.inJustDecodeBounds = false;
            Bitmap originalBitmap = BitmapFactory.decodeFile(inputPath, options);
            
            if (originalBitmap == null) {
                Log.e(TAG, "无法读取图片: " + inputPath);
                return false;
            }
            
            // 保存新图片（不携带EXIF信息）
            FileOutputStream fos = new FileOutputStream(outputPath);
            originalBitmap.compress(Bitmap.CompressFormat.JPEG, 95, fos);
            fos.flush();
            fos.close();
            
            // 覆盖原图
            if (overwriteOriginal) {
                File tempFile = new File(outputPath);
                File originalFile = new File(inputPath);
                
                if (originalFile.delete() && tempFile.renameTo(originalFile)) {
                    Log.d(TAG, "敏感信息抹除成功，已覆盖原图");
                } else {
                    Log.e(TAG, "无法覆盖原图");
                    return false;
                }
            }
            
            return true;
            
        } catch (Exception e) {
            Log.e(TAG, "抹除敏感信息失败: " + e.getMessage());
            return false;
        }
    }
    
    /**
     * 选择性抹除敏感信息
     * @param inputPath 输入图片路径
     * @param outputPath 输出图片路径
     * @param eraseCameraModel 是否抹除相机型号
     * @param eraseDate 是否抹除拍摄日期
     * @param eraseMaker 是否抹除制造商
     * @param eraseFlash 是否抹除闪光灯信息
     * @return boolean 是否成功
     */
    public static boolean eraseSpecificInfo(String inputPath, String outputPath, 
                                        boolean eraseCameraModel, boolean eraseDate, 
                                        boolean eraseMaker, boolean eraseFlash) {
        try {
            ExifInterface exif = new ExifInterface(inputPath);
            
            if (eraseCameraModel) {
                exif.setAttribute(ExifInterface.TAG_MODEL, null);
            }
            
            if (eraseDate) {
                exif.setAttribute(ExifInterface.TAG_DATETIME, null);
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                    exif.setAttribute(ExifInterface.TAG_DATETIME_ORIGINAL, null);
                    exif.setAttribute(ExifInterface.TAG_DATETIME_DIGITIZED, null);
                }
            }
            
            if (eraseMaker) {
                exif.setAttribute(ExifInterface.TAG_MAKE, null);
            }
            
            if (eraseFlash) {
                exif.setAttribute(ExifInterface.TAG_FLASH, null);
            }
            
            exif.saveAttributes();
            return true;
            
        } catch (IOException e) {
            Log.e(TAG, "选择性抹除失败: " + e.getMessage());
            return false;
        }
    }
    
    /**
     * 获取所有EXIF信息（调试用）
     * @param imagePath 图片路径
     * @return Map 所有EXIF信息
     */
    public static Map<String, String> getAllExifInfo(String imagePath) {
        Map<String, String> exifMap = new HashMap<>();
        
        try {
            ExifInterface exif = new ExifInterface(imagePath);
            
            // 常用EXIF标签
            String[] tags = {
                ExifInterface.TAG_MAKE,
                ExifInterface.TAG_MODEL,
                ExifInterface.TAG_DATETIME,
                ExifInterface.TAG_FLASH,
                ExifInterface.TAG_FOCAL_LENGTH,
                ExifInterface.TAG_GPS_LATITUDE,
                ExifInterface.TAG_GPS_LONGITUDE,
                ExifInterface.TAG_ISO_SPEED_RATINGS,
                ExifInterface.TAG_WHITE_BALANCE,
                ExifInterface.TAG_ORIENTATION
            };
            
            for (String tag : tags) {
                String value = exif.getAttribute(tag);
                if (value != null) {
                    exifMap.put(tag, value);
                }
            }
            
        } catch (IOException e) {
            Log.e(TAG, "读取EXIF信息失败: " + e.getMessage());
        }
        
        return exifMap;
    }
    
    /**
     * 检查图片是否包含敏感信息
     * @param imagePath 图片路径
     * @return boolean 是否包含敏感信息
     */
    public static boolean hasSensitiveInfo(String imagePath) {
        PhotoPrivacyInfo info = getSensitiveInfo(imagePath);
        return info.hasSensitiveInfo;
    }
    
    /**
     * 批量抹除文件夹内所有图片的敏感信息
     * @param folderPath 文件夹路径
     * @param recursive 是否递归处理子文件夹
     * @return int 成功处理的文件数量
     */
    public static int batchEraseSensitiveInfo(String folderPath, boolean recursive) {
        int successCount = 0;
        File folder = new File(folderPath);
        
        if (!folder.exists() || !folder.isDirectory()) {
            return 0;
        }
        
        File[] files = folder.listFiles();
        if (files == null) return 0;
        
        for (File file : files) {
            if (file.isFile() && isImageFile(file.getName())) {
                if (eraseSensitiveInfo(file.getAbsolutePath(), null)) {
                    successCount++;
                }
            } else if (file.isDirectory() && recursive) {
                successCount += batchEraseSensitiveInfo(file.getAbsolutePath(), true);
            }
        }
        
        return successCount;
    }
    
    /**
     * 判断是否为图片文件
     * @param filename 文件名
     * @return boolean 是否为图片
     */
    private static boolean isImageFile(String filename) {
        String lower = filename.toLowerCase();
        return lower.endsWith(".jpg") || lower.endsWith(".jpeg") || 
               lower.endsWith(".png") || lower.endsWith(".bmp") ||
               lower.endsWith(".webp");
    }
}